package com.spring.demo.core.dao.jdbc;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import com.spring.demo.core.dao.IFoundDao;

@Repository
public class FoundDao implements IFoundDao {

	private JdbcTemplate jdbcTemplate;

	@Autowired
	public void setDateSource(
			@Qualifier("embeddedDataSource") DataSource dataSource) {
		jdbcTemplate = new JdbcTemplate(dataSource);
	}

	@Override
	public void doTransfor(Long fromAccountId, Long toAccountId, int balance) {
		String updateSql = "update account set balance=? where id=?";

		// 账户1的余额减去balance
		verifyAccount(fromAccountId);
		int fromAccountNewBalance = getAccountBalance(fromAccountId) - balance;
		if (fromAccountNewBalance < 0) {
			throw new RuntimeException(
					"from account's balance should be greater than " + balance);
		}
		jdbcTemplate.update(updateSql, fromAccountNewBalance, fromAccountId);

		// 账户2的余额加上balance
		verifyAccount(toAccountId);
		int toAccountNewBalance = getAccountBalance(toAccountId) + balance;
		jdbcTemplate.update(updateSql, toAccountNewBalance, toAccountId);
	}

	@Override
	public void verifyAccount(Long accountId) {

		try {
			jdbcTemplate.queryForObject("select 1 from account where id=?",
					Integer.class, accountId);
		} catch (DataAccessException e) {
			throw new RuntimeException("account " + accountId
					+ " does not exists!");
		}
	}

	@Override
	public int getAccountBalance(Long accountId) {

		return jdbcTemplate.queryForObject(
				"select balance from account where id=?", Integer.class,
				accountId);
	}
}
